package com.markhsiu.MiniMQ.broker.factory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.markhsiu.MiniMQ.channel.ChannelProcessor;

/**
 * Created by Mark Hsiu on 2017/2/9.
 */
public class BrokerFactory {

    /**
     * 注册的消费者信息
     *  Map
     *    String 消费者ID
     *    List topic订阅主题
     */
    private  final Map<String,List<String>> consumers = new HashMap<>();
    
    /**
     * 消费者连接信息
     */
    private  final Map<String, ChannelProcessor> consumerConnections = new HashMap<>();
    
    /**
     * 单例模式
     */
    private final static BrokerFactory factory = new BrokerFactory();
    private BrokerFactory(){ }
    
    public static BrokerFactory instance(){
    	return factory;
    }
    

    //---------------  消费者订阅管理
    public synchronized boolean  removeConsumer(String consumerID) {
    	if(consumers.containsKey(consumerID)){
    		consumers.remove(consumerID);
    		return true;
    	}
		
    	System.out.println("消费者移除失败："+consumerID);
    	return false;
	}
    
    public  Map<String,List<String>>  getAllConsumers() {
    	return consumers;
	}
    
    public synchronized boolean addConsumer(String consumerID){
    	 
    	if(consumers.containsKey(consumerID)){
    		System.out.println("同名消费者已存在："+consumerID);
    		return false;
    	}
    	
    	consumers.put(consumerID, new ArrayList<>());
    	return true;
    }
    
    public synchronized boolean addConsumerSubscribeTopic(String consumerID,String topic){
    	List<String> topics = consumers.get(consumerID);
    	if(topics == null){
    		boolean flag = addConsumer(consumerID);
    		if(!flag){
    			return false;
    		}
    		topics = consumers.get(consumerID);
    	}
    	topics.add(topic);
    	return true;
    }
    
    public synchronized boolean removeConsumerSubscribeTopic(String consumerID,String topic){
    	List<String> topics = consumers.get(consumerID);
    	if(topics == null){
    		System.out.println("消费者:"+consumerID+" 不存在或已经清楚");
    		return false;
    	}
    	if(topics.remove(topic)){
    		return true;
    	}
    	
    	System.out.println("消费者："+consumerID+" 取消订阅的主题："+topic+ " 不存在");
    	return false;
    }
    
    //---------------  消费者连接管理
    public synchronized void addConsumerConnection(String consumerID, ChannelProcessor channel){
    	 consumerConnections.put(consumerID, channel);
    }
    
    public synchronized void removeConsumerConnection(String consumerID){
   	 	consumerConnections.remove(consumerID);
    }
    
    public ChannelProcessor getConsumerConnection(String consumerID){
   	 	return consumerConnections.get(consumerID);
    }
}
